package wssapp

import (
	"gitee.com/captials-team/ubdframe/src/apps"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/pkg/gin_http"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"github.com/gin-gonic/gin"
	"go.uber.org/dig"
	"net/http"
)

type ApiServer struct {
	*apps.ApiServer
	di   *dig.Container
	conf *configstc.WebsocketAppConfig
	l    v1log.ILog

	wsConnectEntry http.HandlerFunc //连接入口处理func

	gin_http.CorsOption
}

func (s *ApiServer) Name() string {
	return "wss_server"
}

func (s *ApiServer) SetWsHandler(f http.HandlerFunc) {
	s.wsConnectEntry = f
}

func (s *ApiServer) InitRouter() {
	s.Engine().GET("ping", gin_http.PingHandler)
	s.InitRouterForGin(s.Engine())
}

func (s *ApiServer) InitRouterForGin(engine *gin.Engine) {
	var g = engine.Group("")
	if len(s.conf.RoutePrefix) > 0 {
		g = engine.Group(s.conf.RoutePrefix)
	}

	s.router(g)

	return
}

func (s *ApiServer) router(g gin.IRouter) {
	g.Use(
		gin_http.PanicHandler,
		gin_http.QPSLimiterHandler(10, 10),
	)

	//websocket
	common.ErrPanic(s.di.Invoke(func() {
		g.GET("/ws/online", func(ctx *gin.Context) {
			if s.wsConnectEntry != nil {
				s.wsConnectEntry(ctx.Writer, ctx.Request)
			}
			s.l.Warn("ws online not support")
			ctx.String(http.StatusNotFound, "")
		})
	}))
}

func (s *ApiServer) Start() error {
	if !s.Module() {
		s.InitRouter()
	}
	return s.ApiServer.Start()
}

func (s *ApiServer) Stop() error {
	return s.ApiServer.Stop()
}

func NewApiServer(di *dig.Container, conf *configstc.WebsocketAppConfig, logger v1log.ILog) *ApiServer {
	s := &ApiServer{
		di:        di,
		conf:      conf,
		l:         logger,
		ApiServer: apps.NewApiServer(gin.Default(), conf.ApiServer),
	}

	s.ApiServer.WithCors()

	return s
}
